package impl

import (
	"context"

	"gitee.com/go-course/go11/devcloud-mini/cmdb/apps/resource"
	"go.mongodb.org/mongo-driver/bson"
)

// 创建资源
func (i *impl) CreateResource(ctx context.Context, in *resource.Resource) (
	*resource.Resource, error) {
	in.MakeDefault()

	// 自己补充校验规则

	_, err := i.col.InsertOne(ctx, in)
	if err != nil {
		return nil, err
	}

	return in, nil
}

// 查询资源
func (i *impl) QueryResource(ctx context.Context, in *resource.QueryResourceRequest) (
	*resource.ResourceSet, error) {
	filter := bson.M{}

	res, err := i.col.Find(ctx, filter)
	if err != nil {
		return nil, err
	}

	set := &resource.ResourceSet{}
	for res.Next(ctx) {
		ins := resource.NewResource()
		err := res.Decode(ins)
		if err != nil {
			return nil, err
		}
		set.Items = append(set.Items, ins)
	}
	return set, nil
}
